package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// OrderController 订单控制器
type OrderController struct {
	web.Controller
}

// List 获取订单列表
func (c *OrderController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取分页参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}
	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	// 获取过滤参数
	filters := make(map[string]interface{})

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	if keyword := c.GetString("keyword"); keyword != "" {
		filters["keyword"] = keyword
	}
	if storeId, err := c.GetInt64("store_id"); err == nil && storeId > 0 {
		// 如果指定了门店ID，需要验证该门店是否属于当前加盟商
		if permResult.Admin.FranchiseId > 0 {
			store, err := models.GetStoreById(storeId)
			if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = map[string]interface{}{
					"success": false,
					"message": "无权查看该门店的订单",
				}
				c.ServeJSON()
				return
			}
		}
		filters["store_id"] = storeId
	}
	if status, err := c.GetInt8("status"); err == nil && status > 0 {
		filters["status"] = status
	}
	if paymentStatus, err := c.GetInt8("payment_status"); err == nil && paymentStatus > 0 {
		filters["payment_status"] = paymentStatus
	}

	// 查询订单列表
	orders, total, stats, err := models.GetOrderList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取订单列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"list":       orders,
			"total":      total,
			"statistics": stats,
		},
	}
	c.ServeJSON()
}

// GetOne 获取订单详情
func (c *OrderController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取订单ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的订单ID",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetOrderById(id)
	if err != nil || order == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单不存在或获取失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取订单所属的门店
		store, err := models.GetStoreById(order.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权查看该订单",
			}
			c.ServeJSON()
			return
		}
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    order,
	}
	c.ServeJSON()
}

// UpdateStatus 更新订单状态
func (c *OrderController) UpdateStatus() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		Id     int64  `json:"id"`
		Status int8   `json:"status"`
		Remark string `json:"remark"`
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetOrderById(req.Id)
	if err != nil || order == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单不存在或获取失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取订单所属的门店
		store, err := models.GetStoreById(order.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权修改该订单",
			}
			c.ServeJSON()
			return
		}
	}

	// 更新订单状态
	err = models.UpdateOrderStatus(req.Id, req.Status, req.Remark, permResult.Admin.Username)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新订单状态失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新订单状态成功",
	}
	c.ServeJSON()
}

// GetPendingOrders 获取待处理订单列表
func (c *OrderController) GetPendingOrders() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取分页参数
	page, _ := strconv.Atoi(c.GetString("page", "1"))
	pageSize, _ := strconv.Atoi(c.GetString("pageSize", "10"))

	// 构建过滤条件
	filters := make(map[string]interface{})
	filters["status"] = models.OrderStatusPending // 只查询待处理订单

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 关键字搜索
	if keyword := c.GetString("keyword"); keyword != "" {
		filters["keyword"] = keyword
	}

	// 门店过滤
	if storeId, err := c.GetInt64("store_id"); err == nil && storeId > 0 {
		// 如果指定了门店ID，需要验证该门店是否属于当前加盟商
		if permResult.Admin.FranchiseId > 0 {
			store, err := models.GetStoreById(storeId)
			if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = map[string]interface{}{
					"success": false,
					"message": "无权查看该门店的订单",
				}
				c.ServeJSON()
				return
			}
		}
		filters["store_id"] = storeId
	}

	// 查询订单列表
	orders, total, _, err := models.GetOrderList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取待处理订单列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"list":  orders,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetStatistics 获取订单统计数据
func (c *OrderController) GetStatistics() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取查询参数
	startDate := c.GetString("startDate")
	endDate := c.GetString("endDate")
	storeId, _ := c.GetInt64("storeId")

	// 构建过滤条件
	filters := make(map[string]interface{})

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	if startDate != "" {
		startTime, _ := time.Parse("2006-01-02", startDate)
		filters["start_time"] = startTime.Unix()
	}
	if endDate != "" {
		endTime, _ := time.Parse("2006-01-02", endDate)
		filters["end_time"] = endTime.AddDate(0, 0, 1).Unix() // 包含结束日期
	}

	// 验证门店权限
	if storeId > 0 {
		if permResult.Admin.FranchiseId > 0 {
			// 验证门店是否属于当前加盟商
			store, err := models.GetStoreById(storeId)
			if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = map[string]interface{}{
					"success": false,
					"message": "无权查看该门店的统计数据",
				}
				c.ServeJSON()
				return
			}
		}
		filters["store_id"] = storeId
	}

	// 获取统计数据
	stats, err := models.GetOrderStatistics(permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取订单统计数据失败",
		}
		c.ServeJSON()
		return
	}

	// 获取状态分布
	statusData, err := models.GetOrderStatusDistribution(filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取订单状态分布失败",
		}
		c.ServeJSON()
		return
	}

	// 获取支付方式分布
	paymentData, err := models.GetPaymentTypeDistribution(filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取支付方式分布失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"totalOrders": stats.TotalOrders,
			"totalAmount": stats.TotalAmount,
			"todayOrders": stats.TodayOrders,
			"todayAmount": stats.TodayAmount,
			"statusData":  statusData,
			"paymentData": paymentData,
		},
	}
	c.ServeJSON()
}

// GetById 获取订单详情
func (c *OrderController) GetById() {
	// 获取订单ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的订单ID",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetOrderById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    order,
	}
	c.ServeJSON()
}

// CheckVenueAvailability 检查场地可用性
func (c *OrderController) CheckVenueAvailability() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	venueId, _ := c.GetInt64("venue_id")
	startTime, _ := c.GetInt64("start_time")
	endTime, _ := c.GetInt64("end_time")

	if venueId == 0 || startTime == 0 || endTime == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "缺少必要的参数",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		venue, err := models.GetVenueById(venueId)
		if err != nil || venue == nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "场地不存在",
			}
			c.ServeJSON()
			return
		}
		
		// 检查场地是否属于当前加盟商
		store, err := models.GetStoreById(venue.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权查看该场地",
			}
			c.ServeJSON()
			return
		}
	}

	// 检查场地可用性
	isAvailable, err := models.CheckVenueAvailability(venueId, startTime, endTime, 0)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "检查场地可用性失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"available": isAvailable,
		},
	}
	c.ServeJSON()
}

// Update 更新订单信息
// CreateByAdmin 管理员代客下单
func (c *OrderController) CreateByAdmin() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		StoreId   int64  `json:"store_id"`
		VenueId   int64  `json:"venue_id"`
		MemberId  int64  `json:"member_id"`
		StartTime int64  `json:"start_time"`
		EndTime   int64  `json:"end_time"`
		Remark    string `json:"remark"`
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数校验
	if req.StoreId == 0 || req.VenueId == 0 || req.MemberId == 0 || req.StartTime == 0 || req.EndTime == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "缺少必要的参数",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		store, err := models.GetStoreById(req.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权为该门店下单",
			}
			c.ServeJSON()
			return
		}
	}

	// 创建订单
	order, err := models.CreateOrderByAdmin(permResult.Admin.FranchiseId, req.StoreId, req.VenueId, req.MemberId, req.StartTime, req.EndTime, req.Remark, permResult.Admin.Username)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "下单成功",
		"data":    order,
	}
	c.ServeJSON()
}

// Reschedule 换场地
func (c *OrderController) Reschedule() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		OriginalOrderID int64 `json:"original_order_id"`
		NewVenueID      int64 `json:"new_venue_id"`
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetOrderById(req.OriginalOrderID)
	if err != nil || order == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单不存在或获取失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 {
		// 获取订单所属的门店
		store, err := models.GetStoreById(order.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权修改该订单",
			}
			c.ServeJSON()
			return
		}
	}

	// 执行换场地操作
	newOrder, err := models.RescheduleOrder(req.OriginalOrderID, req.NewVenueID, permResult.Admin.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "换场地失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "换场地成功",
		"data":    newOrder,
	}
	c.ServeJSON()
}

func (c *OrderController) Update() {
	// 获取订单ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的订单ID",
		}
		c.ServeJSON()
		return
	}

	// 解析请求数据
	var updateData models.Order
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &updateData); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "请求数据格式错误",
		}
		c.ServeJSON()
		return
	}

	// 确保ID一致
	updateData.Id = id

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 更新订单信息
	if err := models.UpdateOrderStatus(id, updateData.Status, updateData.Remark, admin.Username); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回成功结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "订单更新成功",
	}
	c.ServeJSON()
}
